package src.com.neusoft.nep.controller;

import javafx.beans.property.SimpleStringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.stage.Stage;
import src.com.neusoft.nep.common.AQI;
import src.com.neusoft.nep.common.AdAlertUtils;
import src.com.neusoft.nep.common.FileUtils;
import src.com.neusoft.nep.entity.ProvidedData;

import java.io.IOException;
import java.net.URL;
import java.util.*;

public class ProvinceAQIStatisticsController {
    @FXML
    private ComboBox<String> cmbProvince;
    @FXML
    private ComboBox<String> cmbCity;
    @FXML
    private Button btn_date, btn_pro;
    @FXML
    private TableView<Map<String, String>> tableView;
    @FXML
    private TableColumn<Map<String, String>, String> colNumber, colProvince, colCity, colSO2, colCO, colPM, colAQI;

    private ObservableList<Map<String, String>> tableList = FXCollections.observableArrayList();
    private Map<String, ProvidedData> dataMap; // 存储读取的数据
    private AQI aqiAnalyzer = new AQI(); // 创建AQI分析器实例

    public void initialize() {
        try {
            // 从文件读取数据到Map
            dataMap = FileUtils.readMapObject("AdminData.txt");

            if (dataMap == null || dataMap.isEmpty()) {
                throw new RuntimeException("数据文件为空或读取失败");
            }

            // 初始化表格列
            setupTableColumns();

            // 初始化下拉框
            initializeComboBoxes();

            // 默认加载全国统计数据
            loadAllRegionsData();

        } catch (Exception e) {
            System.err.println("初始化控制器失败: " + e.getMessage());
            e.printStackTrace();
            AdAlertUtils.showDialog("系统错误", "初始化界面失败，请检查数据文件格式");
        }
    }

    private void setupTableColumns() {
        colNumber.setCellValueFactory(cellData ->
                new SimpleStringProperty(cellData.getValue().get("number")));
        colProvince.setCellValueFactory(cellData ->
                new SimpleStringProperty(cellData.getValue().get("province")));
        colCity.setCellValueFactory(cellData ->
                new SimpleStringProperty(cellData.getValue().get("city")));
        colSO2.setCellValueFactory(cellData ->
                new SimpleStringProperty(cellData.getValue().get("so2ExceedCount")));
        colCO.setCellValueFactory(cellData ->
                new SimpleStringProperty(cellData.getValue().get("coExceedCount")));
        colPM.setCellValueFactory(cellData ->
                new SimpleStringProperty(cellData.getValue().get("pmExceedCount")));
        colAQI.setCellValueFactory(cellData ->
                new SimpleStringProperty(cellData.getValue().get("aqiExceedCount")));
    }

    private void initializeComboBoxes() {
        // 初始化省份下拉框数据
        List<String> provinces = new ArrayList<>(REGION_DATA.keySet());
        cmbProvince.setItems(FXCollections.observableList(provinces));

        // 绑定省份选择事件
        cmbProvince.valueProperty().addListener((observable, oldValue, newValue) -> onProvinceChanged());

        // 初始状态：城市下拉框置空
        cmbCity.setItems(FXCollections.emptyObservableList());
    }

    // 加载全国所有地区统计数据
    private void loadAllRegionsData() {
        // 按地区统计超标数量
        Map<String, RegionExceedStats> regionStats = calculateRegionExceedStats();

        // 将统计结果转换为表格数据
        convertStatsToTableData(regionStats);

        // 将数据加载到表格
        tableView.setItems(tableList);
    }

    // 按地区统计超标数量
    private Map<String, RegionExceedStats> calculateRegionExceedStats() {
        Map<String, RegionExceedStats> regionStats = new HashMap<>();

        for (Map.Entry<String, ProvidedData> entry : dataMap.entrySet()) {
            String regionKey = entry.getKey();
            ProvidedData data = entry.getValue();

            // 从ProvidedData获取地区信息
            String province = data.getProvince();
            String city = data.getCity();

            // 构建地区统计键
            String statsKey = province + "-" + city;

            // 获取或创建地区统计对象
            RegionExceedStats stats = regionStats.computeIfAbsent(
                    statsKey,
                    k -> new RegionExceedStats(province, city)
            );

            // 提取污染物浓度
            double so2 = Double.parseDouble(data.getSo2());
            double co = Double.parseDouble(data.getCo());
            double pm = Double.parseDouble(data.getPm());

            // 计算污染物等级
            int so2Level = aqiAnalyzer.getLevel(so2, "so2");
            int coLevel = aqiAnalyzer.getLevel(co, "co");
            int pmLevel = aqiAnalyzer.getLevel(pm, "pm");

            // 计算AQI等级（取最大值）
            int aqiLevel = Math.max(Math.max(so2Level, coLevel), pmLevel);

            // 更新超标计数（等级≥3为超标）
            if (so2Level >= 3) stats.so2ExceedCount++;
            if (coLevel >= 3) stats.coExceedCount++;
            if (pmLevel >= 3) stats.pmExceedCount++;
            if (aqiLevel >= 3) stats.aqiExceedCount++;
        }

        return regionStats;
    }

    // 将统计结果转换为表格数据
    private void convertStatsToTableData(Map<String, RegionExceedStats> regionStats) {
        tableList.clear();
        int counter = 1;

        // 按省份-城市排序
        List<String> sortedKeys = new ArrayList<>(regionStats.keySet());
        Collections.sort(sortedKeys);

        for (String key : sortedKeys) {
            RegionExceedStats stats = regionStats.get(key);

            Map<String, String> row = new HashMap<>();
            row.put("number", String.valueOf(counter++));
            row.put("province", stats.province);
            row.put("city", stats.city);
            row.put("so2ExceedCount", String.valueOf(stats.so2ExceedCount));
            row.put("coExceedCount", String.valueOf(stats.coExceedCount));
            row.put("pmExceedCount", String.valueOf(stats.pmExceedCount));
            row.put("aqiExceedCount", String.valueOf(stats.aqiExceedCount));

            tableList.add(row);
        }
    }

    // 按选择的省份和城市筛选数据
    public void distribute() {
        String province = cmbProvince.getValue();
        String city = cmbCity.getValue();

        // 检查是否选择了省份和城市
        if (province == null || province.isEmpty()) {
            AdAlertUtils.showDialog("操作提示", "请先选择省份");
            return;
        }
        if (city == null || city.isEmpty()) {
            AdAlertUtils.showDialog("操作提示", "请先选择城市");
            return;
        }

        try {
            // 按地区统计超标数量
            Map<String, RegionExceedStats> regionStats = calculateRegionExceedStats();

            // 筛选指定省份和城市的统计结果
            String regionKey = province + "-" + city;
            RegionExceedStats selectedStats = regionStats.get(regionKey);

            if (selectedStats != null) {
                // 仅显示选中地区的统计结果
                tableList.clear();
                Map<String, String> row = new HashMap<>();
                row.put("number", "1");
                row.put("province", selectedStats.province);
                row.put("city", selectedStats.city);
                row.put("so2ExceedCount", String.valueOf(selectedStats.so2ExceedCount));
                row.put("coExceedCount", String.valueOf(selectedStats.coExceedCount));
                row.put("pmExceedCount", String.valueOf(selectedStats.pmExceedCount));
                row.put("aqiExceedCount", String.valueOf(selectedStats.aqiExceedCount));

                tableList.add(row);
                AdAlertUtils.showDialog("查询结果", "成功显示 " + province + " - " + city + " 的超标统计");
            } else {
                AdAlertUtils.showDialog("查询结果", "未找到 " + province + " - " + city + " 的相关记录");
            }
        } catch (Exception e) {
            e.printStackTrace();
            AdAlertUtils.showDialog("系统错误", "数据查询失败: " + e.getMessage());
        }
    }

    public void date() throws IOException {
        Stage stage = new Stage();
        FXMLLoader fxmlLoader = new FXMLLoader();
        URL url = getClass().getResource("../view/ProvinceAQIDate.fxml");
        fxmlLoader.setLocation(url);
        Parent root = fxmlLoader.load();

        Scene scene = new Scene(root);
        stage.setScene(scene);
        stage.showAndWait();
    }

    @FXML
    private void onProvinceChanged() {
        String selectedProvince = cmbProvince.getValue();
        if (selectedProvince == null) {
            cmbCity.setItems(FXCollections.emptyObservableList());
            return;
        }

        List<String> cities = REGION_DATA.get(selectedProvince);
        if (cities != null) {
            ObservableList<String> cityList = FXCollections.observableArrayList(cities);
            cmbCity.setItems(cityList);
            cmbCity.setValue(null); // 清空已选城市
        } else {
            cmbCity.setItems(FXCollections.emptyObservableList());
        }
    }

    // 全国省份、城市数据
    private static final Map<String, List<String>> REGION_DATA = new HashMap<>();

    static {
        // 江苏省
        List<String> jiangsuCities = Arrays.asList(
                "南京市", "无锡", "徐州", "常州", "苏州",
                "南通", "连云港", "淮安", "盐城", "扬州",
                "镇江", "泰州", "宿迁"
        );
        REGION_DATA.put("江苏省", jiangsuCities);

        // 浙江省
        List<String> zhejiangCities = Arrays.asList(
                "杭州", "宁波", "温州", "嘉兴", "湖州",
                "绍兴", "金华", "衢州", "舟山", "台州", "丽水"
        );
        REGION_DATA.put("浙江省", zhejiangCities);

        // 广东省
        List<String> guangdongCities = Arrays.asList(
                "广州", "深圳", "珠海", "汕头", "佛山",
                "韶关", "湛江", "肇庆", "江门", "茂名",
                "惠州", "梅州", "汕尾", "河源", "阳江",
                "清远", "东莞", "中山", "潮州", "揭阳", "云浮"
        );
        REGION_DATA.put("广东省", guangdongCities);

        // 四川省
        List<String> sichuanCities = Arrays.asList(
                "成都", "自贡", "攀枝花", "泸州", "德阳",
                "绵阳", "广元", "遂宁", "内江", "乐山",
                "南充", "眉山", "宜宾", "广安", "达州",
                "雅安", "巴中", "资阳", "阿坝藏族羌族自治州",
                "甘孜藏族自治州", "凉山彝族自治州"
        );
        REGION_DATA.put("四川省", sichuanCities);

        // 辽宁省
        List<String> liaoningCities = Arrays.asList(
                "沈阳", "大连", "鞍山", "抚顺", "本溪",
                "丹东", "锦州", "营口", "阜新", "辽阳",
                "盘锦", "铁岭", "朝阳", "葫芦岛"
        );
        REGION_DATA.put("辽宁省", liaoningCities);

        // 吉林省
        List<String> jilinCities = Arrays.asList(
                "长春", "吉林", "四平", "辽源", "通化",
                "白山", "松原", "白城", "延边朝鲜族自治州"
        );
        REGION_DATA.put("吉林省", jilinCities);

        // 黑龙江省
        List<String> heilongjiangCities = Arrays.asList(
                "哈尔滨", "齐齐哈尔", "鸡西", "鹤岗", "双鸭山",
                "大庆", "伊春", "佳木斯", "七台河", "牡丹江",
                "黑河", "绥化", "大兴安岭地区"
        );
        REGION_DATA.put("黑龙江省", heilongjiangCities);

        // 山东省
        List<String> shandongCities = Arrays.asList(
                "济南", "青岛", "淄博", "枣庄", "东营",
                "烟台", "潍坊", "济宁", "泰安", "威海",
                "日照", "临沂", "德州", "聊城", "滨州", "菏泽"
        );
        REGION_DATA.put("山东省", shandongCities);

        // 山西省
        List<String> shanxiCities = Arrays.asList(
                "太原", "大同", "阳泉", "长治", "晋城",
                "朔州", "晋中", "运城", "忻州", "临汾", "吕梁"
        );
        REGION_DATA.put("山西省", shanxiCities);

        // 河北省
        List<String> hebeiCities = Arrays.asList(
                "石家庄", "唐山", "秦皇岛", "邯郸", "邢台",
                "保定", "张家口", "承德", "沧州", "廊坊", "衡水"
        );
        REGION_DATA.put("河北省", hebeiCities);

        // 湖南省
        List<String> hunanCities = Arrays.asList(
                "长沙", "株洲", "湘潭", "衡阳", "邵阳",
                "岳阳", "常德", "张家界", "益阳", "郴州",
                "永州", "怀化", "娄底", "湘西土家族苗族自治州"
        );
        REGION_DATA.put("湖南省", hunanCities);

        // 湖北省
        List<String> hubeiCities = Arrays.asList(
                "武汉", "黄石", "十堰", "宜昌", "襄阳",
                "鄂州", "荆门", "孝感", "荆州", "黄冈",
                "咸宁", "随州", "恩施土家族苗族自治州", "仙桃",
                "潜江", "天门", "神农架林区"
        );
        REGION_DATA.put("湖北省", hubeiCities);

        // 安徽省
        List<String> anhuiCities = Arrays.asList(
                "合肥", "芜湖", "蚌埠", "淮南", "马鞍山",
                "淮北", "铜陵", "安庆", "黄山", "滁州",
                "阜阳", "宿州", "六安", "亳州", "池州", "宣城"
        );
        REGION_DATA.put("安徽省", anhuiCities);

        // 福建省
        List<String> fujianCities = Arrays.asList(
                "福州", "厦门", "莆田", "三明", "泉州",
                "漳州", "南平", "龙岩", "宁德"
        );
        REGION_DATA.put("福建省", fujianCities);

        // 江西省
        List<String> jiangxiCities = Arrays.asList(
                "南昌", "景德镇", "萍乡", "九江", "新余",
                "鹰潭", "赣州", "吉安", "宜春", "抚州", "上饶"
        );
        REGION_DATA.put("江西省", jiangxiCities);

        // 河南省
        List<String> henanCities = Arrays.asList(
                "郑州", "开封", "洛阳", "平顶山", "安阳",
                "鹤壁", "新乡", "焦作", "濮阳", "许昌",
                "漯河", "三门峡", "南阳", "商丘", "信阳", "周口", "驻马店", "济源"
        );
        REGION_DATA.put("河南省", henanCities);

        // 其他省份...
    }

    // 地区超标统计类
    private static class RegionExceedStats {
        String province;
        String city;
        int so2ExceedCount = 0;
        int coExceedCount = 0;
        int pmExceedCount = 0;
        int aqiExceedCount = 0; // 重命名为aqiExceedCount以反映实际含义

        public RegionExceedStats(String province, String city) {
            this.province = province;
            this.city = city;
        }
    }
}